package fr.mav.gamecardcounter.Activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import fr.mav.gamecardcounter.Game;
import fr.mav.gamecardcounter.R;
import fr.mav.gamecardcounter.Round;
import fr.mav.gamecardcounter.ScoreAdapter;
import fr.mav.gamecardcounter.Team;
import fr.mav.gamecardcounter.TypeOfGame;

/**
 * Created by Quentin on 28/07/13.
 */
public class BeloteGameActivity extends Activity {

    private Game game;
    private ScoreAdapter scoreAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_belote_game);
        setupGame();
        Toast.makeText(this, game.getTypeOfGame().toString(), Toast.LENGTH_LONG).show();
    }

    private void setupGame() {
        game = new Game();
        game.setTypeOfGame(TypeOfGame.Belote);
        initializeGame(4);
    }

    private void initializeGame(int nbPlayer) {
        game.setNbPlayer(nbPlayer);

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater inflater = getLayoutInflater();
        builder.setTitle(R.string.legend_alert_dialog_teamname_game_activity);
        final View view = inflater.inflate(R.layout.alert_dialog_teamname, null);
        builder.setView(view)
                .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                    }
                });
        final AlertDialog alertDialog = builder.create();
        alertDialog.show();
        Button cancelButton = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
        cancelButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String teamName1 = ((EditText) view.findViewById(R.id.teamname_1)).getText().toString();
                String teamName2 = ((EditText) view.findViewById(R.id.teamname_2)).getText().toString();
                if (teamName1 != null && !teamName1.isEmpty()) {
                    if (teamName2 != null && !teamName2.isEmpty()) {
                        creatTeam(teamName1, teamName2);
                        alertDialog.dismiss();
                    } else {
                        Toast.makeText(getApplicationContext(), R.string.error_name_team_2, Toast.LENGTH_LONG).show();
                    }
                } else {
                    Toast.makeText(getApplicationContext(), R.string.error_name_team_1, Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    public void creatTeam(String name1, String name2) {
        ArrayList<Team> teams = new ArrayList<Team>();
        teams.add(new Team(0, name1));
        teams.add(new Team(0, name2));
        game.setTeams(teams);
        TextView nameTeam1 = (TextView) findViewById(R.id.label_team_name1);
        nameTeam1.setText(name1);
        TextView nameTeam2 = (TextView) findViewById(R.id.label_team_name2);
        nameTeam2.setText(name2);
        ArrayList<Round> rounds = new ArrayList<Round>();
        game.setRounds(rounds);
        ListView listView = (ListView) findViewById(R.id.listview_score);
        scoreAdapter = new ScoreAdapter(this, game.getRounds());
        listView.setAdapter(scoreAdapter);

        final Handler h2 = new Handler();
        Runnable run = new Runnable() {
            long starttime=System.currentTimeMillis();
            TextView timer=(TextView) findViewById(R.id.timer);
            @Override
            public void run() {
                long millis = System.currentTimeMillis() - starttime;
                int seconds = (int) (millis / 1000);
                int minutes = seconds / 60;
                seconds     = seconds % 60;
                timer.setText(String.format("%d:%02d", minutes, seconds));
                h2.postDelayed(this, 500);
            }
        };
        run.run();
    }

    public void addScore(View view1) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater inflater = getLayoutInflater();
        builder.setTitle(R.string.label_enter_score);
        final View view = inflater.inflate(R.layout.alert_dialog_add_score, null);
        builder.setView(view).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int id) {
            }
        }).setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int id) {
            }
        });
        final AlertDialog alertDialog = builder.create();
        alertDialog.show();
        Button validButton = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
        validButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String team1score = ((EditText) view.findViewById(R.id.new_score_team1)).getText().toString();
                String team2score = ((EditText) view.findViewById(R.id.new_score_team2)).getText().toString();
                if (team1score != null && !team1score.isEmpty()) {
                    if (team2score != null && !team2score.isEmpty()) {
                        int score1 = Integer.parseInt(team1score);
                        int score2 = Integer.parseInt(team2score);
                        if (score1 >= 0 && score2 >= 0) {
                            setscore(score1, score2);
                            alertDialog.dismiss();
                        } else {
                            Toast.makeText(getApplicationContext(), R.string.error_invalid_score, Toast.LENGTH_LONG).show();
                        }
                    } else {
                        Toast.makeText(getApplicationContext(), R.string.error_name_team_2, Toast.LENGTH_LONG).show();
                    }
                } else {
                    Toast.makeText(getApplicationContext(), R.string.error_name_team_1, Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    private void setscore(int score1, int score2) {
        ArrayList<Round> rounds = game.getRounds();
        rounds.add(new Round(score1, score2, game.getRounds().size() + 1));
        Collections.sort(rounds, new CustomComparator());
        scoreAdapter.notifyDataSetChanged();
        TextView scoreteam1 = (TextView) findViewById(R.id.label_score_team_name1);
        TextView scoreteam2 = (TextView) findViewById(R.id.label_score_team_name2);
        int score1tot = score1 + Integer.parseInt(scoreteam1.getText().toString());
        scoreteam1.setText("" + score1tot);

        int score2tot = score2 + Integer.parseInt(scoreteam2.getText().toString());
        scoreteam2.setText("" + score2tot);

        if (score1tot > score2tot && score1tot>=1001) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(getString(R.string.Team)+" "+game.getTeams().get(0).getName()+" "+getString(R.string.Win));
            builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int id) {
                        }
                    }).show();

        }else if (score2tot > score1tot && score2tot>=1001) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(getString(R.string.Team)+" "+game.getTeams().get(1).getName()+" "+getString(R.string.Win));
            builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int id) {
                        }
                    }).show();
        }else if(score2tot == score1tot && score2tot>=1001) {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle(R.string.Equality);
                builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                    }
                }).show();
        }


        if (rounds.size() == 1) {
            LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linear_layout_listview);
            LayoutInflater inflater = getLayoutInflater();
            View v = inflater.inflate(R.layout.separator, linearLayout, false);
            linearLayout.addView(v);
        }
    }

    public class CustomComparator implements Comparator<Round> {
        @Override
        public int compare(Round o1, Round o2) {
            return o2.getNbRound().compareTo(o1.getNbRound());
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        overridePendingTransition(0, 0);
    }


}
